#pragma once

#include <vector>
#include <string>

#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "./include/mysql.h"

namespace ns_model
{
    using namespace std;
    using namespace ns_log;
    using namespace ns_util;

    struct Question
    {
        string number; // 题目编号
        string title;  // 标题
        string star;   // 题目难度
        string desc;   // 题目描述
        string head;   // 用户代码
        string tail;   // 测试代码
        int cpu_limit; // 时间限制
        int mem_limit; // 空间限制
    };

    const string oj_questions = "oj_questions";
    const string host = "localhost";
    // const string user = "ml";
    // const string passwd = "Qwertyuiop.123";
    const string user = "root";
    const string passwd = "";
    const string db = "oj";
    const int port = 3306;

    class Model
    {
    private:
        bool QueryMySql(const string &sql, vector<Question> *out)
        {
            MYSQL *my = mysql_init(NULL);
            if (nullptr == mysql_real_connect(my, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, NULL, 0))
            {
                LOG(FALSE) << "数据库加载失败" << endl;
                return false;
            }
            LOG(INFO) << "数据库加载成功" << endl;
            mysql_set_character_set(my, "utf8");

            if (0 != mysql_query(my, sql.c_str()))
            {
                LOG(FALSE) << "sql执行出错" << endl;
                return false;
            }

            MYSQL_RES *res = mysql_store_result(my);
            int rows = mysql_num_rows(res);
            int cols = mysql_num_fields(res);

            Question q;

            for (int i = 0; i < rows; i++)
            {
                MYSQL_ROW row = mysql_fetch_row(res);
                q.number = row[0];
                q.title = row[1];
                q.star = row[2];
                q.desc = row[3];
                q.head = row[4];
                q.tail = row[5];
                q.cpu_limit = atoi(row[6]);
                q.mem_limit = atoi(row[7]);

                out->push_back(q);
            }

            free(res);
            mysql_close(my);

            return true;
        }

    public:
        bool GetAllQuestions(vector<Question> *out)
        {
            string sql = "select * from ";
            sql += oj_questions;

            return QueryMySql(sql, out);
        }
        bool GetOneQuestion(const string &number, Question *q)
        {
            string sql = "select * from ";
            sql += oj_questions;
            sql += " where number=";
            sql += number;
            vector<Question> out;
            if (QueryMySql(sql, &out))
            {
                if (out.size() == 1)
                {
                    *q = out[0];
                    return true;
                }
            }
            return false;
        }
    };
}